<?php

namespace fankers;

use fankers\helper\Log;
use fankers\lib\github\Github as GithubBase;

class Github
{
    public $_inst = null;
    public $_class = null;

    public function __construct($params)
    {
        ##用code 获取token信息
        $this->_class = GithubBase::class;

        if (!$this->_inst) {
            $this->_inst = new $this->_class($params);
        }
    }

    /**
     * 判断类是否似可调用的
     * @param $action
     * @return bool
     */
    protected function isCall($action)
    {
        if (is_callable([$this->_inst,$action])) {
            return true;
        } else {
            return false;
        }
    }

    public function index()
    {
        ## code=CODE&state=STATE 确认授权以后跳转到当前方法 带着code

        ## 生成code
        $this->_inst->start();
        $code = $_GET['code'];
        $params = [
            'code' => $code,
        ];


        $result = $userInfo = $openidInfo = [];

        ## 获取token
        if ($this->isCall('token')) {
            $result = $this->_inst->token($params);
        }

        Log::debug($result,'/tmp/fkk_qq_token_log');

        ## 用返回的token信息 拉取用户信息
        if (!empty($result)) {
            if ($this->isCall('info')){
                $apiData['access_token'] = $result['access_token'];
                $apiData['scope'] = $result['scope'];
                $userInfo = $this->_inst->info($apiData);
            }
        }

        return $userInfo;
    }
}
